<?php

namespace App\Http\ControllersAdmin;

use Phalcon\Mvc\Controller;
use App\Util\Fun;
use \App\Service\NodesAuthService;
use App\Service\CommentService;
class BaseController extends Controller
{
	protected $f;
	protected $city_id;

	//初始化
	protected function initialize(){
		$this->f = new Fun;
        $this->checkAuth();
        $this->getCityId();
	}
    
    //根据头部获取city_id 默认为成都 63
	protected function getCityId()
	{
		$city_id = $this->request->getHeader('City-Id');
		$this->city_id = $city_id ? intval($city_id) : 63;
	}
	
    //检查权限
    protected function checkAuth(){
        if(strpos($this->request->getURI(),'admin/common')) return true;

        $users = $this->getUser();

        if($users->member_id == 1)
            return true;
       
        //redis查询权限
        $key = "EW_NODE". strtoupper(str_replace('/','_',$this->request->getURI()));
        $node_id = (int)$this->redis->get($key);
        if($this->redis->sIsMember("EW_ROLES_{$users->role_id}",$node_id))
        	return TRUE;

        //数据库查询权限
        $auth = NodesAuthService::checkAuth($users->role_id, $this->request->getURI());
        if ($auth)
        	return TRUE;

       	$this->echoJson('You do not have permission',401);
    }
	
	//验证数据
	protected function validation($validation,$raw){
		if(empty($raw)){
			$raw = new \stdClass();
		}
		$messages = $validation->validate($raw);
		if(count($messages)){
			$i=0;
			$msg = [];
			foreach ($messages as $message) {
				++$i;
				$msg[]="$i: $message;";
			}
			$msg = implode('',$msg);
			$this->echoJson($msg,401);
		}
		$data = !$validation->getData() ?  new \stdClass() : $validation->getData();
		if(property_exists($this,'user') && $this->user ){
			$data->member_id = $this->user->member_id;
			$data->avatar = isset($data->avatar) ? $data->avatar : $this->user->avatar;
			$data->nickname = isset($data->nickname) ? $data->nickname : $this->user->nickname;
		}
		return $data;
		
	}
	
	protected function echoJson($data,$code = 0){
		empty($data) && $data = new \stdClass();
		if(is_array($data)){
			// isset($data['list']) && empty($data['list']) && $data['list'] = new \stdClass();
			isset($data['list']) && empty($data['list']) && $data['list'] = [];
		}
		$this->f->echoJson($data,$code);
	}
	
	//获取用户
	protected function getUser($auth = 1){
		$sub = $this->session->get('sub');
		if($auth && empty($sub)){
			$this->echoJson("jwt not empty",401);
		}
		$this->user = $sub;
		return $sub;
	}
	
	protected function sql(){
		$sql = $this->di->get('profiler')->getProfiles();
		print_r($sql);
		exit;
	}

    /**
     * [getFullUrl 获取完整url]
     * @param  [type]  $old_url       [原始url]
     * @param  boolean $is_https      [是否采用https]
     * @param  [type]  $self_prefix   [采用自定义前缀]
     * @return [type]                 [description]
     */
    public function getFullUrl($old_url, $is_https = FALSE, $self_prefix = NULL)
    {
        return $this->f->getFullUrl($old_url, $is_https, $self_prefix);
    }
    
    protected function backgroudDateFilterByCityRole(&$para,$filter=true){
        if($filter){
            error_reporting(0);
            $user=$this->getUser(1);
            if( $user->roles_info && $user->roles_info->city_id>0){
                $para->city_id=$user->roles_info->city_id;
            }
        }
    }
    /*生成假评论*/
    protected function makeShamComments($data){
        CommentService::makeShamComments($data);
    }
    /*获取假评论的随机用户*/
    protected function getRandomUser($limitno){
        $sql = "SELECT id FROM ew_user where creator_id = -1 AND role_id = 1 ORDER BY RAND() LIMIT {$limitno}";
        return (new Fun)->db_execute($sql);
    }
	/*add operater log*/
    protected function addOperateLogs($logSysRecord){
        date_default_timezone_set('PRC');
        if(!array_key_exists('uid',$logSysRecord)){
            $users = $this->getUser();
            $logSysRecord['uid']=$users->member_id;
        }
        if(!array_key_exists('add_time',$logSysRecord)){
            $logSysRecord['add_time']=date("Y-m-d H:i:s");
        }
        CommentService::addOperateLog($logSysRecord);
    }
    /*查询封装 只有select查询*/
    protected function excuteSqlQuery($sql,$para){
        $countno=0;
        $p=1;$page_num=10;
        if(isset($para->p)){
            $p=intval($para->p);
        }
        if(isset($para->page_num)){
            $page_num=intval($para->page_num);
        }
        if($p>0){
            $count=(new Fun)->db_execute(" select count(*) nos from ({$sql}) coutnotemp");//分页总数统计
            if($count){
                $countno=$count[0]->nos;
            }
            $offset=(intval($p)-1)*$page_num;
            $sql.=" limit {$offset},".$page_num;
        }
        $data= (new Fun)->db_execute($sql);
        $assign = [
            'total' => $countno,
            'list'  => $data
        ];
        return $assign;
    }
}
